import express from 'express';
import { userListDB, roomListDB, roomUserDB, msgListDB, friendListDB } from '../../nedb/index.mjs';
import jwt from 'jsonwebtoken';
import { TOKEN_KEY, TIME } from '../../config/jwt/index.mjs';
import { handleFind, handleInsert } from '../../utils/handleDB.mjs';
import { socketMap } from '../../utils/handleSocket.mjs';
// import { getSocket } from '../../utils/handleSocket.mjs';

const router = express.Router();

// 用户注册
router.post('/out/user/userRegiste', (req, res) => {
	const { userId } = req.body;
	roomUserDB.insert({});

	handleFind(userListDB, { userId })
		.then((findRes) => {
			if (findRes.length > 0) {
				res.operationSuccess('failure', '', '账号已存在');
				return;
			}

			const roomId = new Date().getTime();
			const arr = [
				handleInsert(roomListDB, { roomId }),
				handleInsert(userListDB, { userId: userId }),
				handleInsert(roomUserDB, { roomId, userId: userId }),
			];

			Promise.all(arr).then((promiseRes) => {
				res.operationSuccess('success', '', '注册成功');
			});
		})
		.catch((err) => {
			res.operationFailed(err);
		});
});

// 用户登录
router.post('/out/user/userLogin', (req, res) => {
	const { userId } = req.body;
	handleFind(userListDB, { userId })
		.then((findRes) => {
			if(findRes.length !== 1) {
				res.operationSuccess('failure', 'ERR_200', '账号不存在或异常');
			} else {
				const token = jwt.sign({ userId }, TOKEN_KEY, { expiresIn: TIME });

				handleFind(msgListDB, { userId: findRes[0] })
				res.operationSuccess('success', '', '登录成功', { token, userData: {
					userId: findRes[0].userId,
					msgHistory: {}
				}});
			}
		})
		.catch((err) => res.operationFailed(err));
});

// 好友推荐
router.get('/user/friendRecommand', (req, res) => {
	const { userId } = req.query;
	handleFind(userListDB, {})
		.then((findRes) => {
			console.log('findRes', findRes);
			res.operationSuccess(
				'success',
				'',
				'获取成功',
				findRes.filter((item) => item.userId !== userId),
			);
		})
		.catch((err) => {
			res.operationFailed(err);
		});
});

// 添加好友
router.get('/user/addFriend', (req, res) => {
	const { userId, friendId } = req.query;

	const roomId = new Date().getTime();

	const data = {
		from: userId,
		to: friendId,
		status: 'unAccept',
		msg: `${userId} 请求添加您为好友`,
	};

	const arr = [
		handleInsert(roomListDB, { roomId }),
		handleInsert(roomUserDB, [
			{ roomId, userId: userId },
			{ roomId, userId: friendId },
		]),
		handleInsert(friendListDB, data),
	];

	Promise.all(arr)
		.then(() => {
			handleFind(friendListDB, { $or: [{ form: friendId }, { to: friendId }] })
				.then((friendList) => {
					console.log('friendList', friendList, friendId);
					const _s = socketMap[friendId];
					if (_s) {
						// _s.sendMsg(data, 'friendRequest', friendList);
						_s.io.to(friendId).emit('friendRequest', friendList);
					}
					res.operationSuccess('success', '', '添加成功');
				})
				.catch((err) => {
					res.operationFailed(err);
				});
		})
		.catch((err) => {
			res.operationFailed(err);
		});
});

// 获取好友请求列表
router.get('/user/getFriendRequestList', (req, res) => {
	const { userId } = req.query;
	handleFind(friendListDB, { $or: [{ form: userId }, { to: userId }] })
		.then((friendList) => {
			res.operationSuccess('success', '', '添加成功', friendList);
		})
		.catch((err) => {
			res.operationFailed(err);
		});
});

export default router;
